import { login, logout, getInfo, refreshToken } from '@/api/login'
import {getToken, setToken, setExpiresIn, removeToken, setName, getName} from '@/utils/auth'
import {keepalive} from "@/api/api";

const user = {
  state: {
    token: getToken(),
    name: getName(),
    avatar: '',
    roles: [],
    permissions: [], // 从 auth utils 获取
    // 新增: 用于存储定时器 ID
    keepAliveTimer: null
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_CUSTOMER: (state, customer) => {
      state.customer = customer
    },
    SET_DATAPERMISSIONS: (state, dataPermissions) => {
      state.dataPermissions = dataPermissions
    },
    SET_KEEP_ALIVE_TIMER: (state, timerId) => {
      state.keepAliveTimer = timerId;
    },
    // 新增: 清除定时器 ID
    CLEAR_KEEP_ALIVE_TIMER: (state) => {
      if (state.keepAliveTimer) {
        clearInterval(state.keepAliveTimer); // 清除定时器
      }
      state.keepAliveTimer = null;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      return new Promise((resolve, reject) => {
        login(username, password).then(res => {
          let data = res.data
          setToken(data.token)
          setName(username)

          commit('SET_NAME', username)
          commit('SET_TOKEN', data.token)
          setExpiresIn(999999)
          commit('SET_EXPIRES_IN', 999999)
          // dispatch('StartKeepAliveTimer');
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          console.log(res)
          const user = res.user
          // const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : user.avatar;
          const avatar = user.avatar;
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          if (res.customer!=null && res.customer!=''){
            commit('SET_CUSTOMER', res.customer)
          }else {
            commit('SET_CUSTOMER', null)
          }
          commit('SET_DATAPERMISSIONS',res.dataPermissions)
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 刷新token
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        refreshToken(state.token).then(res => {
          setExpiresIn(res.data)
          commit('SET_EXPIRES_IN', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
// 新增: 启动保活定时器 Action
    StartKeepAliveTimer({ commit, state, dispatch }) {
      // 先清除可能存在的旧定时器
      commit('CLEAR_KEEP_ALIVE_TIMER');

      // 只有在有 token 的情况下才启动
      if (state.token) {
        const interval = 10000; // 每 5 分钟 ping 一次
        const timerId = setInterval(() => {
          dispatch('KeepAlive');
        }, interval);
        commit('SET_KEEP_ALIVE_TIMER', timerId);
      }
    },
    KeepAlive({ state }) {
      // 检查 token 是否存在，以防万一
      if (state.token) {
        console.log('Sending keep-alive ping...');
        keepalive({username: state.name, token: state.token}).then(() => {
          console.log('Keep-alive ping successful.');
        }).catch(error => {
          console.error('Keep-alive ping failed:', error);
        });
      } else {
        console.warn('No token found, cannot send keep-alive ping.');
        // 如果没 token 了，应该清除定时器（虽然理论上 Logout 时会清）
        // dispatch('StopKeepAliveTimer'); // 避免 StopKeepAliveTimer 调用自身
        commit('CLEAR_KEEP_ALIVE_TIMER');
      }
    },
    // 新增: 停止保活定时器 Action (主要给 Logout 调用)
    StopKeepAliveTimer({ commit }) {
      commit('CLEAR_KEEP_ALIVE_TIMER');
    },
    // 退出系统
    LogOut({ commit, state }) {
      console.log(state)
      return new Promise((resolve, reject) => {
        logout({
          username: state.name,
          token: state.token
        }).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          // dispatch('StopKeepAliveTimer');
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
